package com.zygh.lz.stapprove;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.zygh.lz.entity.PcLog;
import com.zygh.lz.service.PcLogService;
import com.zygh.lz.util.JwtTokenUtil;
import com.zygh.lz.util.JwtUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;

@Aspect
@Component
public class SysPcLogAspect {
    @Resource
    private PcLogService pcLogService;
    @Resource
    private JwtUtils jwtUtils;

    /**
     * 切点
     */
    @Pointcut("@annotation(com.zygh.lz.stapprove.SysPcLog)")
    public void pointCut(){}

    @AfterReturning(value = "pointCut()",returning = "obj")
    public void savePcLog(JoinPoint joinPoint,Object obj){
        PcLog pcLog = new PcLog();

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 客户端ip
        String ip = SysLogAspect.getRemoteIP(request);

        //String token = request.getHeader("token");

        //String tokenHead = "Bearer";
        //token = token.substring(tokenHead.length());
        String token = request.getHeader(jwtUtils.getHeader());

        String userName = jwtUtils.getClaimByToken(token).getSubject();

        // 拦截的方法请求参数
        String param = Arrays.toString(joinPoint.getArgs());

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        //获取操作--方法上的ViLog的值
        SysPcLog sysPcLog = method.getAnnotation(SysPcLog.class);

        if(Objects.nonNull(sysPcLog)){
            pcLog.setOperation(sysPcLog.operation());
            pcLog.setModule(sysPcLog.module());
        }
        pcLog.setUrl(request.getRequestURI());
        pcLog.setIp(ip);
        pcLog.setRequestParam(param);
        pcLog.setUserName(userName);
        pcLog.setRequestDate(DateUtil.now());
        pcLog.setReponseContent(JSONUtil.toJsonStr(obj));

        pcLogService.save(pcLog);
    }
}
